package com.dld.protocol.image;

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpStatus;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Process;
import android.util.Log;
import android.widget.ImageView;

import com.app.cache.FileUltility;
import com.dld.android.net.Callback;
import com.dld.android.net.Http;
import com.dld.android.net.Param;
import com.dld.android.util.Tools;

public class ImageProtocol {
	private static Map<String, List<ImageView>> cacheMap = new Hashtable<String, List<ImageView>>();
	private static ExecutorService pool = Executors.newFixedThreadPool(5);
	private String cacheKey;
	private Context context;
	Handler handler = new Handler();
	private Http http;
	private Param param;
	private String url;
	private DbCache dcache;

	public ImageProtocol(Context paramContext, String paramString) {
		this.context = paramContext;
		this.url = paramString;
		this.cacheKey = paramString;
		dcache = DbCache.getInstance(context);

	}

	public ImageProtocol(Context paramContext, String paramString1,
			String paramString2) {
		this.context = paramContext;
		this.url = paramString1;
		this.cacheKey = ("img:" + paramString2);
	}

	private void notifyRcvBmp(final String path, final String url) {
		handler.post(new Runnable() {
			public void run() {
				List<ImageView> childs = cacheMap.get(url);
				for (int i = 0; i < childs.size(); i++) {
					ImageView imcv = childs.get(i);
					int targetHeight = imcv.getMeasuredHeight();
					int targetwidth = imcv.getMeasuredWidth();
					Bitmap bmp = ImageViewFill.fillImageView(path, targetwidth,
							targetHeight);
					if (bmp != null) {
						imcv.setImageBitmap(bmp);
					} else {
						File file = new File(path);
						file.delete();
						DbCache.getInstance(context).delCacheFile(url);
					}
				}
			}
		});

	}

	public Param getParam() {
		if (this.param == null)
			this.param = new Param();
		return this.param;
	}

	public void startTrans(final ImageView paramImageView) {
		final String url = ImageProtocol.this.url;
		Context cnt = paramImageView.getContext();
		final String path = FileUltility.converUrlToPath(cnt, url);
		if (dcache.isCached(url)) {
			Bitmap bmp = ImageViewFill.fillImageView(path, paramImageView
					.getMeasuredWidth(), paramImageView.getMeasuredHeight());
			if (bmp != null) {
				paramImageView.setImageBitmap(bmp);
			} else {
				File file = new File(path);
				file.delete();
				DbCache.getInstance(context).delCacheFile(url);
				ConnectivityManager cm = (ConnectivityManager) cnt
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				if (cm.getActiveNetworkInfo().isAvailable()) {
					ImageProtocol imp = new ImageProtocol(context, url);
					imp.startTrans(paramImageView);
				}
			}
		} else {
			if (url == null || "".equals(url)) {
				return;
			}
			List<ImageView> list_childs = cacheMap.get(url);
			if (list_childs != null) {
				list_childs.add(paramImageView);
			} else {
				list_childs = new Vector<ImageView>();
				list_childs.add(paramImageView);
				cacheMap.put(url, list_childs);
				pool.submit(new Runnable() {
					public void run() {
						try {
							Process
									.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
							String localpath = FileUltility.converUrlToPath(
									paramImageView.getContext(), url);
							FileOutputStream fout = new FileOutputStream(path);
							URL u = new URL(url);
							HttpURLConnection http = (HttpURLConnection) u
									.openConnection();
							if (http.getResponseCode() == HttpStatus.SC_OK) {
								FileUltility.saveFileToCache(http
										.getInputStream(), localpath);
								// cache this file to cache list
								DbCache.getInstance(context).cacheFile(url);
								notifyRcvBmp(localpath, url);
							} else {
								throw new Exception(
										"NetWork Exception  not read");
							}
						} catch (Exception e) {
							e.printStackTrace();
							File file = new File(path);
							file.delete();
							DbCache.getInstance(context).delCacheFile(url);
						}
						Process
								.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
						System.gc();
					}

				});
			}
		}
	}

	private class ImageCallback extends Callback {
		public ImageCallback() {
			this.custom = true;
		}

		public Context getContext() {
			return ImageProtocol.this.context;
		}

		public Param getHeader() {
			return null;
		}

		public byte[] getPostParam() {
			return null;
		}

		public String getUrl() {
			return ImageProtocol.this.url;
		}

		public void onException(Exception paramException) {
			Tools.printException(paramException);
		}

		public void onRecieve(byte[] paramArrayOfByte) {
		}
	}
}
